package com.chagee.store.operation.server.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.TimeInterval;
import com.alibaba.arms.tracing.Span;
import com.alibaba.arms.tracing.Tracer;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.chagee.store.operation.api.enums.PayTypeEnum;
import com.chagee.store.operation.server.entity.StoreSettlementDO;
import com.chagee.store.operation.server.event.dao.WorkOrderMapper;
import com.chagee.store.operation.server.event.service.StoreSettlementBaseService;
import com.chagee.store.operation.server.service.biz.StoreSettlementBizService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 刷新结算单支付途径
 * @Author : hk
 * @Date : 2025/5/7
 */

@Slf4j
@Component
public class RefreshSettlementPayChannelHandler {


	@Resource
	private StoreSettlementBizService storeSettlementBizService;

	@Resource
	private StoreSettlementBaseService storeSettlementBaseService;

	@Resource
	private WorkOrderMapper workOrderMapper;

	/**
	 * 刷新结算单支付途径
	 * @param param
	 * @return
	 */
	@XxlJob("refreshSettlementPayChannel")
	public ReturnT<String> refreshSettlementPayChannel(String param) {
		Span span = Tracer.builder().getSpan();
		TimeInterval timer = cn.hutool.core.date.DateUtil.timer();
		log.info("刷新结算单支付途径定时任务开始,traceId :{}", span.getTraceId());
		try {
			if (StringUtils.isNotBlank(param)) {
				//结算单号
				List<String> settlementNos = Arrays.stream(param.split(",")).map(String::trim).filter(StringUtils::isNotBlank).collect(Collectors.toList());
				if (CollectionUtil.isNotEmpty(settlementNos)) {
					List<StoreSettlementDO> storeSettlementDOS = storeSettlementBaseService.batchQuerySettlement(settlementNos);
					updateSettlementPayChannel(storeSettlementDOS);
				}
			}else {
				long startIndex = 0L;
				while (true) {
					List<StoreSettlementDO> storeSettlementDOS = storeSettlementBaseService.querySettlementsByPayNo(startIndex);
					if (CollectionUtils.isEmpty(storeSettlementDOS)) {
						break;
					}
					log.info("刷新结算单支付途径定时任务 :{}", JSON.toJSONString(storeSettlementDOS));

					updateSettlementPayChannel(storeSettlementDOS);

					startIndex = Math.toIntExact(storeSettlementDOS.stream().map(StoreSettlementDO::getId).max(Comparator.naturalOrder()).orElse(0L));
				}
			}

			log.info("刷新结算单支付途径定时任务结束，共耗时:{},TraceId:{}", timer.intervalRestart(), span.getTraceId());
		} catch (Exception e) {
			XxlJobLogger.log("刷新结算单支付途径定时任务异常，异常信息:", e);
			log.error("刷新结算单支付途径定时任务异常 => param : {} => 异常信息 :", param, e);
		}
		XxlJobLogger.log("刷新结算单支付途径定时任务结束，共耗时:{},TraceId:{}", timer.intervalRestart(), span.getTraceId());
		return ReturnT.SUCCESS;
	}

	public void updateSettlementPayChannel(List<StoreSettlementDO> storeSettlementDOS) {
		storeSettlementDOS.forEach(s -> {
			LambdaUpdateWrapper<StoreSettlementDO> wrapper = new LambdaUpdateWrapper<>();
			wrapper.eq(StoreSettlementDO::getId, s.getId());
			wrapper.set(StoreSettlementDO::getPayType, PayTypeEnum.ONLINE.getType());
			storeSettlementBaseService.update(wrapper);
		});
	}
}
